package core.api;

import jade.util.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import core.tool.PropertyAccountit;

public  class DbManager {
	
	private Logger log = Logger.getJADELogger(this.getClass().getName());
	private String userDb, pwdDb, urlDb, driverDb, nameDb;
	private Connection dbCon;
	private boolean connectionOpen = false;
	
	public DbManager() {
		
		// inizializzo le variabili di ambiente
		Properties prodb = new PropertyAccountit().load();
		userDb = prodb.getProperty("DB_USER");
		pwdDb = prodb.getProperty("DB_PASSWORD");
		nameDb = prodb.getProperty("DB_NAME");
		urlDb = prodb.getProperty("DB_URL");
		driverDb = prodb.getProperty("DB_DRIVER");
	}
	
	public Connection open() {
		if (!connectionOpen){
		
			
			log.info("Apro la connessione al db di inventario (Db Portale): name="+nameDb + " user="+userDb);
			try {
				Class.forName(driverDb);
			} catch (ClassNotFoundException e) {
				log.info("Classe del driver (oracle o mysql) non trovata");
				e.printStackTrace();
			}
			try {
				dbCon = DriverManager.getConnection(urlDb+nameDb, userDb,pwdDb);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			connectionOpen= true;
			log.info("Aperta la connessione al db con successo");
		}
		return dbCon;

	}

	public void close()  {
		try {
			dbCon.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("Chiusa la connessione al db di inventario (Db Portale)");
		connectionOpen = false;
	}
	

	

}
